<?php

namespace api\controller;

use common\model\NoteModel;
use common\model\TagModel;
use common\service\DemandChangeService;
use common\service\DemandOrderService;
use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\ReviewFeedbackEntityService;
use common\service\StepCategoryService;
use common\service\StepService;
use common\validate\ReviewFeedback;
use common\validate\DemandOrder;
use support\ErrorCode;
use think\Exception;
use think\Response;
use think\Request;

class DemandOrderController extends VerifyController
{

    /**
     * @var \common\service\DemandOrderService
     */
    private $demandOrderService;
    private $reviewFeedbackEntityService;

    public function __construct()
    {
        parent::__construct();
        $this->demandOrderService = DemandOrderService::getInstance();
        $this->reviewFeedbackEntityService = ReviewFeedbackEntityService::getInstance();
    }

    /**
     * 创建/更新 需求单
     * @param \think\Request $request
     * @return \think\Response
     * @throws \Throwable
     * @throws Exception
     */
    public function save(Request $request)
    {
        $param = $request->all();
        $validate = new DemandOrder();
        $validate->scene('Create');
        if (empty($param['data']['demand_order']['id']) && !$validate->check($param)) {
            throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
        }

        $validate->scene('Update');
        if (!empty($param['data']['demand_order']['id']) && !$validate->check($param)) {
            throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
        }

        if (!empty($param['data']['demand_order']['demand_type']) && $param['data']['demand_order']['demand_type'] == "review_feedback") {
            $validate->scene('SaveReviewFeedbackCosMedia');
            if (!empty($param['data']['review_feedback_cos_media'])) {
                foreach ($param['data']['review_feedback_cos_media'] as $reviewFeedbackCosMediaItem) {
                    if (!$validate->check($reviewFeedbackCosMediaItem)) {
                        throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
                    }
                }
            }
        }

        try {
            $req = $this->demandOrderService->save($param['data']);
            return json(success_response('', $req));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取需求单列表
     * @param \think\Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function getDemandOrderList(Request $request)
    {
        $param = $request->all();
        // 除了待我确认的，其他的保持验证project_id必传
        if (empty($param['param']['wait_me_confirm']) || $param['param']['wait_me_confirm'] !== 'yes') {
            $validate = new DemandOrder();
            $validate->scene('GetDemandOrderListWithProjectRequired');
            if (!$validate->check($param)) {
                throw_strack_exception($validate->getError(), ErrorCode::REQUEST_PARAM_ERROR);
            }
        }
        $req = $this->demandOrderService->getDemandOrderList($param["param"]);
        return json(success_response('', $req));
    }


    /**
     * 获取需求单任务情况分组 - 排期
     * @param \think\Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function getDemandOrderListThumbnail(Request $request)
    {
        $param = $request->all();
        $req = $this->demandOrderService->getDemandOrderListThumbnail($param);
        return json(success_response('', $req));
    }

    /**
     * 导入审核反馈
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function import(Request $request)
    {
        $data = $request->all()['data'];
        $validator = new DemandOrder();
        $validator->scene("ImportBaseInfo");
        $showSecondLevelStepCategoryList = StepCategoryService::getInstance()->showSecondLevelList();
        $showSecondLevelStepCategoryList = array_filter($showSecondLevelStepCategoryList, function ($i) use ($data) {
            return $i['module_code'] === $data['module_code'];
        });
        // 获取标签名称
        $reasonTypeList = model(TagModel::class)->field(['name'])->column('name');
        $stepList = StepService::getInstance()->getSteps([], '*');
        $stepList = array_column($stepList, 'id', 'name');
        $res = [];
        $showSecondLevelStepCategoryList[] = [
            'code' => 'entity_demand',
            'name' => '实体需求',
        ];
        foreach ($data['list'] as $listIndex => &$listItem) {
            $res[$listIndex] = [
                'index' => $listItem['index'] ?? $listIndex,
                'err_code' => 0,
                'err_msg' => 'OK',
            ];
            $validator->scene("ImportBaseInfo");
            if (!$validator->check($listItem)) {
                $res[$listIndex]['err_code'] = ErrorCode::REQUEST_PARAM_ERROR;
                $res[$listIndex]['err_msg'] = $validator->getError();
                continue;
            }

            if (isset($listItem['director_star'])) {
                if ($listItem['director_star'] === '是') {
                    $listItem['director_star'] = 'yes';
                } else if ($listItem['director_star'] === '否') {
                    $listItem['director_star'] = 'no';
                } else {
                    unset($listItem['director_star']);
                }
            }

            if (isset($listItem['key_shot'])) {
                if ($listItem['key_shot'] === '是') {
                    $listItem['key_shot'] = 'yes';
                } else if ($listItem['key_shot'] === '否') {
                    $listItem['key_shot'] = 'no';
                } else {
                    unset($listItem['key_shot']);
                }
            }

            if (isset($listItem['enable'])) {
                if ($listItem['enable'] === '启用') {
                    $listItem['enable'] = 'yes';
                } else if ($listItem['enable'] === '废除') {
                    $listItem['enable'] = 'no';
                } else {
                    unset($listItem['enable']);
                }
            }

            if (isset($listItem['is_append'])) {
                if ($listItem['is_append'] === '是') {
                    $listItem['is_append'] = 'yes';
                } else if ($listItem['is_append'] === '否') {
                    $listItem['is_append'] = 'no';
                } else {
                    unset($listItem['is_append']);
                }
            }

            // 绑定方式
            if (!isset($listItem['design_skip_remove_rigging_control']) && !empty($data['module_code']) && $data['module_code'] == 'asset') {
                $listItem['design_skip_remove_rigging_control'] = 'no'; // no 标准绑定,yes 非标准绑定
            }

            $validator->scene("ImportDemand");
            foreach ($showSecondLevelStepCategoryList as $stepCategoryItem) {
                if (!isset($listItem[$stepCategoryItem['code']])) {
                    continue;
                }
                foreach ($listItem[$stepCategoryItem['code']] as &$stepCategoryDemand) {
                    if (!$validator->check($stepCategoryDemand)) {
                        $res[$listIndex]['err_code'] = ErrorCode::REQUEST_PARAM_ERROR;
                        $res[$listIndex]['err_msg'] = $validator->getError();
                        continue;
                    }
                    // 需求类型验证
                    if (isset($stepCategoryDemand['reason_type'])) {
                        if (!in_array($stepCategoryDemand['reason_type'], $reasonTypeList)) {
                            $res[$listIndex]['err_code'] = ErrorCode::NOTE_REASON_TYPE_NOT_FOUND;
                            $res[$listIndex]['err_msg'] = "{$listItem['initial_episode_code']}/{$listItem['showings_number']}/{$listItem['name']}/{$stepCategoryItem['name']}下的{$stepCategoryDemand['reason_type']}返修类型不存在";
                            continue;
                        }
                    }
                    // 返修工序验证
                    if (!empty($stepCategoryDemand['repair_step_name'])) {
                        if (empty($stepList[$stepCategoryDemand['repair_step_name']])) {
                            $res[$listIndex]['err_code'] = ErrorCode::STEP_NOT_EXIST;
                            $res[$listIndex]['err_msg'] = "{$listItem['initial_episode_code']}/{$listItem['showings_number']}/{$listItem['name']}/{$stepCategoryItem['name']}下的{$stepCategoryDemand['repair_step_name']}工序名称不存在";
                            continue;
                        }
                        $stepCategoryDemand['repair_step_id'] = $stepList[$stepCategoryDemand['repair_step_name']];
                    }
                    if (isset($stepCategoryDemand['demand_status'])) {
                        if ($stepCategoryDemand['demand_status'] === '已接受') {
                            $stepCategoryDemand['demand_status'] = NoteModel::DEMAND_STATUS_PENDING;
                        } else if ($stepCategoryDemand['demand_status'] === '已拒绝') {
                            $stepCategoryDemand['demand_status'] = NoteModel::DEMAND_STATUS_REJECTED;
                        } else if ($stepCategoryDemand['demand_status'] === '待确认') {
                            $stepCategoryDemand['demand_status'] = NoteModel::DEMAND_STATUS_DEFAULT;
                        } else {
                            unset($stepCategoryDemand['demand_status']);
                        }
                    }
                }
            }
        }

        $skipNotChange = $data['skip_not_change'] ?? 'no';
        try {
            $res = $this->demandOrderService->import($data['list'], $data['module_code'], $data['review_feedback_id'], $res, $skipNotChange === 'yes');
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 发布
     * @param Request $request
     * @return Response|void
     */
    public function publish(Request $request)
    {
        $param = $request->param()['param'];
        $noteIdList = $param['entity_id_list'];
        $reviewFeedbackId = $param['review_feedback_id'];
        $moduleCode = $param['module_code'];
        $moduleCode = $moduleCode === 'asset' ? 'design' : 'storyboard';
        try {
            $req = $this->demandOrderService->publish($request->getUserId(), $reviewFeedbackId, $moduleCode, $noteIdList);
            return json(success_response('', $req));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }


    /**
     * 删除需求单
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function deleteDemandOrder(Request $request)
    {
        try {
            $filter = $request->all()['param']["filter"];
            if (!is_array($filter['id'])) {
                $filter['id'] = [$filter['id']];
            }
            $res = [];
            foreach ($filter['id'] as $demandOrderId) {
                $res[] = $this->demandOrderService->deleteDemandOrder([
                    'project_id' => $filter['project_id'],
                    'id' => $demandOrderId
                ]);
            }
            if (count($res) == 1 && !is_array($filter['id'])) {
                $res = array_shift($res);
            }
            return json(success_response('', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }


    /**
     * 批量修改需求单条目
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function batchUpdateSameNote(Request $request)
    {
        try {
            $data = $request->all()['data'];
            $req = $this->demandOrderService->batchUpdateSameNote($data);
            return json(success_response('', $req));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 批量移除需求单未发布实体
     * @return Response|void
     * @throws Exception
     */
    public function batchRemoveUnpublishedEntity(Request $request)
    {
        try {
            $data = $request->all()['data'];
            $req = $this->demandOrderService->batchRemoveUnpublishedEntity($data);
            return json(success_response('', $req));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 保存反馈下游返修状态
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function saveNoteDownstreamRepairStatus(Request $request)
    {
        $param = $request->all()['param'];
        $noteEntityRelationId = $param['note_entity_relation_id'];
        $status = $param['repair_accept_status'];
        $req = $this->demandOrderService->saveNoteDownstreamRepairStatus($noteEntityRelationId, $status);
        return json(success_response('', $req));
    }

    /**
     * 需求变更列表
     * @param Request $request
     * @return Response
     */
    public function changeList(Request $request)
    {
        try {
            $data = $request->all()['param'];
            $page = $request->all()['page'] ?? [1, C("database.database_max_select_rows")];
            $req = DemandChangeService::getInstance()->list($data, $page);
            return json(success_response('', $req));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

	/**
	 * 工作台-我的任务-工作待办-需求单统计
	 * @param \think\Request $request
	 *
	 * @return array|void
	 */
	public function getDemandOrderListStatistics(Request $request)
	{
		try {
			$param = $request->post()['param'];
			$userId = $request->getUserId();
			$result = DemandChangeService::getInstance()->getDemandOrderListStatistics($param,$userId);
			return json(success_response('success', $result));
		}catch (LogicException $exception){
			throw_strack_exception($exception->getMessage(), $exception->getCode());
		}
	}
    /**
     * 根据实体entity_id 获取需求单review_feedback_id 列表
     * @param  Request  $request
     * @return array
     */
    public function findDemandOrderIds(Request $request)
    {
        $param = $request->all();
        $entityId = $param['entity_id'] ?? [];
        $result = $this->reviewFeedbackEntityService->getEntityIdByDemandOrderId($entityId);

        return json(success_response('操作成功', $result));
    }

    /**
     * 查询指定的需求内容数据
     * @param  \think\Request  $request
     * @return array
     */
    public function findReviewFeedbackContent(Request $request)
    {
        $param = $request->all()['data'];
        $reviewFeedBackId = $param['review_feedback_id'] ?? [];
        $entityId = $param['entity_id'] ?? [];
        $projectId = $param['project_id'] ?? [];
        $stepCategoryId = $param['step_category_id'] ?? [];

        $result = $this->reviewFeedbackEntityService->getFindReviewFeedbackContent(
            $reviewFeedBackId, $entityId, $projectId, $stepCategoryId
        );

        return json(success_response('操作成功', $result));
    }

    /**
     * 根据需求review_feedback_id 查询需求数据
     * @param \think\Request $request
     * @return \think\Response
     */
    public function getReviewFeedBackList(Request $request)
    {
        $param = $request->all();
        $reviewFeedbackId = $param['review_feedback_id'] ?? [];
        $stepCategoryId = $param['step_category_id'] ?? [];
        $entityId = $param['entity_id'] ?? [];

        $result = $this->reviewFeedbackEntityService->getReviewFeedBackList(
            $reviewFeedbackId, $entityId, $stepCategoryId
        );

        return json(success_response('操作成功', $result));
    }

    /**
     * 需求单的原计划时间,和新的计划时间
     * @param \think\Request $request
     * @return \think\Response
     */
    public function getOriginalNewPublished(Request $request)
    {
        $param = $request->all();
        $reviewFeedBackId = $param['review_feedback_id'] ?? [];
        $taskId = $param['task_id'] ?? [];

        $result = $this->reviewFeedbackEntityService->getOriginalNewPublished($reviewFeedBackId,$taskId);

        return json(success_response('操作成功', $result));
    }

    /**
     * 关闭需求单
     */
    public function closeDemandOrder(Request $request)
    {
        $param = $request->param()['param'];

        try {
            $result = $this->demandOrderService->closeDemandOrder($param['review_feedback_id']);
            return json(success_response('success', $result));
        }catch (LogicException $exception){
            throw_strack_exception($exception->getMessage(), $exception->getCode());
        }
    }
}

